<?php
namespace app\kefu\model;
use think\Model;
use app\kefu\model\KfUser as KfUserModel;

class kfServiceLog extends Model
{
    protected $autoWriteTimestamp = true;
    /**
     * 新增服务记录
     */
    public static function addTrace($fd,$data){
        $kf    = $data['kf'];
        $guest = $data['guest'];
        $data = [
            'shop_id'       => $kf['shop_id']
            ,'fd'           => $fd
            ,'kf_code'      => $kf['code']
            ,'kf_name'      => $kf['name']
            ,'kf_avatar'    => $kf['avatar']
            ,'guest_code'   => $guest['code']
            ,'guest_name'   => $guest['name']
            ,'guest_avatar' => $guest['avatar']
            ,'create_time'  => time()
            ,'update_time'  => 0
        ];
        $count = self::where(['fd'=>$fd,'status'=>1])->count();
        if($count == 0){
            self::create($data);
            KfUserModel::where('code',$kf['code'])->inc('service_num')->update();
        }
    }
    /**
     * 修改服务记录状态
     */
    public static function updateTrace($fd,$data){

        $data = self::where(['fd'=>$fd,'status'=>1])->find();
        if($data){
            self::where(['fd'=>$fd])->update(['status'=>0,'update_time'=>time()]);
            KfUserModel::where('code',$data['kf_code'])->dec('service_num')->update();
        }
    }
    /**
     * 维护FD状态
     */
    public static function statFd($fds){
        //移除不在线FD
        $db_fds = self::where('status','1')->column('fd');
        $diff_fds=array_diff($db_fds,$fds);
        self::whereIn('fd',$diff_fds)->update(['status'=>0,'update_time'=>time()]);
        //统计客户服务数量
        KfUserModel::where('1=1')->update(['service_num'=>0]);
        $res = self::field('kf_code,count(*) AS num')->where('status',1)->group('kf_code')->select();
        foreach ($res as $k => $v) {
            KfUserModel::where('code',$v['kf_code'])->update(['service_num'=>$v['num']]);
        }
    }

}